<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      label {
        display: inline-block;
        width: 60px;
        text-align: right;
      }
      select {
        width: 100px;
      }
    </style>
  </head>
  <body>
    <label for="">省</label>
    <select name="" id="sheng"></select>
    '<label for="">市</label>
    <select name="" id="shi"></select
    >'
  </body>
  <script src="./城市选择.js"></script>
  <script>
    $(function () {
      var sheng = $("#sheng");
      var shi = $("#shi");
      var text = "<option value=''>----请选择----</option>";
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        text += `<option value=  '${item.code}'>  ${item.name}  </option>`;
      }
      sheng.html(text);
      sheng.change(function () {
        var val = $(this).val();
        shi.html("<option value=''>----请选择----</option>");
        if (val != "") {
          for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.code == val) {
              for (var j = 0; j < item.children.length; j++) {
                var ites = item.children[j];
                shi.append(
                  `<option value=  '${ites.code}'>  ${ites.name}  </option>`
                );
              }
            }
          }
        }
      });
      // 省份选择请选择时，清空市的下拉框
      sheng.change(function () {
        if ($(this).val() == "") {
          shi.html("<option value=''>----请选择----</option>");
        }
      });
    });
  </script>
</html>
